package com.chenshu.mycnblog.service;

import com.chenshu.mycnblog.common.Constant;
import com.chenshu.mycnblog.common.SecurityUtil;
import com.chenshu.mycnblog.mapper.UserMapper;
import com.chenshu.mycnblog.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA
 * Description：用户表服务层
 * User：chenshu
 * Date：2024-01-02
 * Time：11:32
 */

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public int registry(UserInfo userInfo) {
        userInfo.setPassword(SecurityUtil.encrypt(userInfo.getPassword()));//密码加盐
        return userMapper.insertUser(userInfo);
    }

    public int login(HttpServletRequest request, String username, String password) {
        UserInfo userInfo = userMapper.selectByUsername(username);
        if (userInfo == null || !SecurityUtil.decrypt(password, userInfo.getPassword())) {
            return -1;
        } else {
            //将userInfo保存到session中
            HttpSession session = request.getSession(true);
            int uid = userInfo.getId();
            session.setAttribute(Constant.SESSION_USERINFO_KEY, uid);
            log.info("存入了session {key: " + Constant.SESSION_USERINFO_KEY + " value: " + uid + "}");
            return 1;
        }
    }

    public UserInfo getUserInfo(Integer id) {
        return userMapper.selectById(id);
    }
}
